package com.example;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class Demo01_DriverManager {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncoding=utf8 " +
                    "&allowPublicKeyRetrieval=true&useSSL=false", "root", "123456");
            statement = connection.createStatement();
            System.out.println("请输入学生姓名");
            Scanner scanner=new Scanner(System.in);
            String name = scanner.next();
            String sql = "select student_id, sn, name, mail, class_id from student where name = '"+ name + "'";
            resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                long stuId= resultSet.getLong(1);
                String stuSn = resultSet.getString(2);
                String stuName = resultSet.getString(3);
                String stuMail = resultSet.getString(4);
                long classId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号={0}，学号={1}，学生姓名={2}，邮箱={3}，班级编号={4}",stuId,stuSn,stuName,stuMail,classId));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
